﻿using System;
using System.Web.UI;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using System.ComponentModel;
using Marbles.Core.Content.Forms;

namespace Marbles.Core.Controls
{
    [ToolboxData("<{0}:UserForm runat=server></{0}:UserForm>")]
    public class UserForm : CompositeControl
    {
        [Category("Form")]
        public string FormName
        {
            get
            {
                object obj = ViewState["FormName"];
                return (obj == null) ? "" : obj.ToString();
            }
            set { ViewState["FormName"] = value; }
        }

        [Category("Form")]
        public Int32 SiteId
        {
            get
            {
                object obj = ViewState["SiteId"];
                return (obj == null) ? 0 : Convert.ToInt32(obj);
            }
            set { ViewState["SiteId"] = value; }
        }

        [Category("Appearance")]
        public Table ChildTable
        {
            get
            {
                this.EnsureChildControls();
                return this.cTblForm;
            }
        }

        [Category("Events")]
        public event EventHandler FormSubmitted;


        private Table cTblForm;
        private Button SaveButton;
        private Marbles.Core.Content.Forms.UserForm questions = null;

        public override void RenderControl(HtmlTextWriter writer)
        {
            this.EnsureChildControls();
            base.RenderControl(writer);

        }

        protected override void CreateChildControls()
        {

            int rowindex = 0;
            cTblForm = new Table();
            cTblForm.ID = "Table";
            cTblForm.ApplyStyle(this.CreateControlStyle());
            if (questions == null) { questions = new Marbles.Core.Content.Forms.UserForm(this.FormName); }

            foreach (Marbles.Core.Content.Forms.Question q in questions)
            {
                TableRow row = new TableRow();
                row.ID = "row_" + rowindex.ToString();
                TableCell cell1 = new TableCell();
                TableCell cell2 = new TableCell();
                TableCell cell3 = new TableCell();
                cell1.ID = "cell_" + rowindex.ToString() + "_0";
                cell2.ID = "cell_" + rowindex.ToString() + "_1";
                cell3.ID = "cell_" + rowindex.ToString() + "_2";
                cell2.Text = "&nbsp;";
                cell3.Controls.Add(q.GetWebControl());
                cell1.Text = q.Id + ") " + q.Text;
                row.Cells.Add(cell1);
                row.Cells.Add(cell2);
                row.Cells.Add(cell3);
                rowindex += 1;
                cTblForm.Rows.Add(row);
            }

            this.Controls.Add(cTblForm);

            SaveButton = new Button();
            SaveButton.Text = "Submit";
            SaveButton.ToolTip = "Submit form.";
            SaveButton.OnClientClick = "SubmitForm();return false;";
            //SaveButton.Click += new EventHandler(FormSubmitted_Click);
            this.Controls.Add(SaveButton);
            Literal lt = new Literal();
            lt.Text = "<script language=\"javascript\" type=\"text/javascript\">" + GetScript() + "</script>";
            lt.ID = "SubmitForm";
            this.Controls.Add(lt);
        }

        protected void FormSubmitted_Click(object sender, EventArgs e)
        {
            if (this.FormSubmitted != null) { FormSubmitted(this, EventArgs.Empty); }
        }

        private string GetScript()
        {
            StringBuilder sb = new StringBuilder();
            if (questions == null) { questions = new Marbles.Core.Content.Forms.UserForm(this.FormName); }

            sb.AppendLine("function SubmitForm() {");
            sb.AppendLine("var value = '';");
            sb.AppendLine("var postData= 'id=' + escape('" + this.FormName + "');");

            foreach (Question q in questions)
            {
                switch (q.QuestionType)
                {
                    case QuestionType.CheckboxList:
                    case QuestionType.RadioButtonList:
                        sb.Append("value = '';");
                        sb.Append("for (i = 0; i < $('#" + this.ClientID + "_" + q.Id + "').find('input:checked').length;i++) {");
                        sb.Append("if (value != '') {value += '$';}");
                        sb.Append("value += $('#" + this.ClientID + "_" + q.Id + "').find('input:checked')[i].value;");
                        sb.Append("}");
                        break;
                    case QuestionType.RadioButton:
                    case QuestionType.Checkbox:
                        sb.Append("value = $('#" + this.ClientID + "_" + q.Id + "')[0].checked;");
                        break;
                    default:
                        sb.Append("value = $('#" + this.ClientID + "_" + q.Id + "').val();");
                        break;
                }
                sb.Append("if (value == null) {value = '';}");
                sb.AppendLine("postData += '&" + q.Id + "=' + escape(value);");
            }

            sb.AppendLine("var response = HttpPostRequest('/UserFormSubmit.axd',postData);");
            sb.AppendLine("if (response == 'OK') {alert('Your response has been submitted.'); window.location.reload();} else {ServerError(response);}");
            sb.AppendLine("}");

            return sb.ToString();
        }
    }
}